using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using WcfExtensions.ServiceModel.Channels;

namespace WcfExtensions.ServiceModel.Description
{
    public class CompressionBehavior : IServiceBehavior, IEndpointBehavior, IDispatchMessageInspector, IClientMessageInspector
    {
        private readonly MessageCompressor _compressor;

        public CompressionBehavior(CompressionAlgorithm algorithm, CompressionLevel level)
        {
            _compressor = new MessageCompressor(algorithm, level);
        }

        public void Validate(ServiceEndpoint endpoint)
        {
        }

        public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(this);
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            clientRuntime.MessageInspectors.Add(this);
        }

        public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
        {
            request = MessageCompressor.DecompressMessage(request);
            return null;
        }

        public void BeforeSendReply(ref Message reply, object correlationState)
        {
            reply = _compressor.CompressMessage(reply);
        }

        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            reply = MessageCompressor.DecompressMessage(reply);
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            request = _compressor.CompressMessage(request);
            return null;
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {

        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
        }
    }
}